import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    TextInput,
    Alert,
    Platform,
    AsyncStorage
} from 'react-native';
import Picker from 'react-native-picker';

import {Theme, ListRow, Overlay, Label, Button, Checkbox} from 'teaset';
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const avatarSource=[];
const {height, width} = Dimensions.get('window');
export default class ModifyLendingInformationPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        if(this.props.id!==undefined){
            this.setState({
                token:this.state.token.concat(message)
            },()=>this.getInfo());
        }else {
            this.setState({
                token:this.state.token.concat(message)
            });
        }
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "lendingId":this.props.id
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/lending/queryOne',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    this.setState({
                        name:responseJson.data.name,
                        IDCard:responseJson.data.idCard,
                        phone:responseJson.data.phone,
                        address:responseJson.data.address,
                        area:responseJson.data.area,
                        loanMoney:responseJson.data.borrowingMoneyStr,
                        repaymentMoney:responseJson.data.repaymentMoneyStr,
                        loanTime:responseJson.data.borrowingTimeStr,
                        repaymentTime:responseJson.data.repaymentTimeStr,
                        remark:responseJson.data.remark
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            name:'',
            IDCard:'',
            phone:'',
            address:'',
            area:'',
            loanMoney:'',
            repaymentMoney:'',
            loanTime:'',
            repaymentTime:'',
            remark:'',
            images:[],
            max:9,
            isSelectL:false
        }
    };

    _showDateBottomPicker=()=>{
        this.setState({
            isSelect:true
        });
        Picker.init({
            pickerConfirmBtnText:'完成',
            pickerCancelBtnText:'取消',
            pickerTitleText:'',
            pickerData: this._createDateData(),
            pickerToolBarFontSize: 16,
            pickerFontSize: 16,
            pickerFontColor: [255, 0 ,0, 1],
            onPickerConfirm: (pickedValue, pickedIndex) => {
                this.setState({
                    repaymentTime:pickedValue,
                    isSelect:false
                })
            },
            onPickerCancel: (pickedValue, pickedIndex) => {
                this.setState({
                    isSelect:false
                })
            },
        });
        Picker.show();
    };

    _createDateData=()=> {
        let date = [];
        for(let i=1950;i<2050;i++){
            let month = [];
            for(let j = 1;j<13;j++){
                let day = [];
                if(j === 2){
                    for(let k=1;k<29;k++){
                        day.push(k+'日');
                    }
                    //Leap day for years that are divisible by 4, such as 2000, 2004
                    if(i%4 === 0){
                        day.push(29+'日');
                    }
                }
                else if(j in {1:1, 3:1, 5:1, 7:1, 8:1, 10:1, 12:1}){
                    for(let k=1;k<32;k++){
                        day.push(k+'日');
                    }
                }
                else{
                    for(let k=1;k<31;k++){
                        day.push(k+'日');
                    }
                }
                let _month = {};
                _month[j+'月'] = day;
                month.push(_month);
            }
            let _date = {};
            _date[i+'年'] = month;
            date.push(_date);
        }
        return date;
    };

    _showDatePicker=()=> {
        this.setState({
            isSelect:true
        });
        Picker.init({
            pickerConfirmBtnText:'完成',
            pickerCancelBtnText:'取消',
            pickerTitleText:'',
            pickerData: this._createDateData(),
            pickerToolBarFontSize: 16,
            pickerFontSize: 16,
            pickerFontColor: [255, 0 ,0, 1],
            onPickerConfirm: (pickedValue, pickedIndex) => {
                this.setState({
                    loanTime:pickedValue,
                    isSelect:false
                })
            },
            onPickerCancel: (pickedValue, pickedIndex) => {
                this.setState({
                    isSelect:false
                })
            },
        });
        Picker.show();
    };


    showPop=(type, modal, text)=>{
        let overlayView = (
            <Overlay.PopView
                style={{alignItems: 'center', justifyContent: 'center'}}
                type={type}
                modal={modal}
                ref={v => this.overlayPopView = v}
            >
                <View style={{backgroundColor: Theme.defaultColor,width:230, alignItems: 'center',borderRadius:10}}>
                    <TouchableOpacity   style={[styles.overlay,{borderTopRightRadius:10, borderTopLeftRadius:10}]}
                                        onPress={() => this.pickSingleWithCamera()}>
                        <Text style={styles.PopMsg}>拍照</Text>
                    </TouchableOpacity>
                    <TouchableOpacity  style={styles.overlay}
                                       onPress={() => this.openPicLib()}>
                        <Text style={styles.PopMsg}>从手机相册中选择</Text>
                    </TouchableOpacity>
                    <TouchableOpacity  style={styles.overlay1}
                                       onPress={() => this.overlayPopView && this.overlayPopView.close()}>
                        <Text style={[styles.PopMsg,{color:'#233333'}]}>取消</Text>
                    </TouchableOpacity>
                </View>
            </Overlay.PopView>
        );
        Overlay.show(overlayView);
    };

    pickSingleWithCamera=()=> {

        this.overlayPopView && this.overlayPopView.close();
    };

    openPicLib=()=> {

        this.overlayPopView && this.overlayPopView.close();
    };

    preservation=()=>{
        if(this.props.id!==undefined){
            var params={
                "token":this.state.token,
                "name":this.state.name,
                "idCard":this.state.IDCard,
                "phone":this.state.phone,
                "address":this.state.address,
                "area":this.state.area,
                "borrowingTimeStr":this.state.loanTime,
                "repaymentTimeStr":this.state.repaymentTime,
                "borrowingMoney":this.state.loanMoney,
                "repaymentMoney":this.state.repaymentMoney,
                "isPublic":false,
                "remark":this.state.remark,
                "id":this.props.id
            };
        }else {
            var params={
                "token":this.state.token,
                "name":this.state.name,
                "idCard":this.state.IDCard,
                "phone":this.state.phone,
                "address":this.state.address,
                "area":this.state.area,
                "borrowingTimeStr":this.state.loanTime,
                "repaymentTimeStr":this.state.repaymentTime,
                "borrowingMoney":this.state.loanMoney,
                "repaymentMoney":this.state.repaymentMoney,
                "isPublic":false,
                "remark":this.state.remark,
            };
        }
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/lending/uploadArrearsAndGetId',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    Actions.LoanPersonalInformationPage({id:responseJson.data})
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    render() {
        return (
            <View style={styles.container}>
                {this.state.isSelect
                    ?(<TouchableOpacity
                        onPress={()=>this.setState({
                            isSelect:false
                        },()=>Picker.hide())}
                        style={{position: 'absolute',top:0, bottom:0,left:0,right:0,
                            backgroundColor:'#000000',opacity:0.2,zIndex:2}}/>)
                    :(null)}
                <View style={styles.titleView}>
                    <Text style={styles.titleMsg}>个人资料</Text>
                    <TouchableOpacity
                        onPress={()=>Actions.pop()}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.GoBack}
                            style={styles.goBackImg}/>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={()=>this.preservation()}
                        style={styles.completeView}>
                        <Text style={styles.completeMsg}>保存</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.dataView}>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>姓        名</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TextInput
                            ref={ (ref)=>this.nameTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.name}
                            placeholder="请输入姓名"
                            placeholderTextColor='#b2b2b2'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    name:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>身份证号</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TextInput
                            ref={ (ref)=>this.IDCardTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.IDCard}
                            placeholder="请输入身份证号"
                            placeholderTextColor='#b2b2b2'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    IDCard:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>手机号码</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TextInput
                            ref={ (ref)=>this.phoneTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.phone}
                            keyboardType={"numeric"}
                            placeholder="请输入手机号"
                            placeholderTextColor='#b2b2b2'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    phone:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>户口地址</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TextInput
                            ref={ (ref)=>this.addressTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.address}
                            placeholder="请填写户口所在地"
                            placeholderTextColor='#b2b2b2'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    address:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>所在地区</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TextInput
                            ref={ (ref)=>this.areaTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.area}
                            placeholder="请填写所在地区"
                            placeholderTextColor='#b2b2b2'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    area:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.labelView}>
                        <Text style={styles.labelLabellingMsg}>借款日期</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TouchableOpacity
                            style={{width:130,height:40,justifyContent:'center'}}
                            onPress={()=>this._showDatePicker()}>
                            {this.state.loanTime===''
                                ?(<View style={{flexDirection:'row',alignItems:'center'}}>
                                    <Text style={[styles.labelInformationMsg,{marginLeft:33}]}>请选择</Text>
                                    <Image
                                        style={{marginLeft:18}}
                                        source={ImageUtil.DropDown}/>
                                </View>)
                                :(<Text style={styles.labelInformationMsg}>{this.state.loanTime}</Text>)}
                        </TouchableOpacity>
                        <Text style={styles.labelMsg}>借款金额</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <View style={{height:40,width:100,justifyContent:'center',alignItems:'center'}}>
                            <TextInput
                                ref={ (ref)=>this.loanMoneyTextInput = ref }
                                autoCapitalize={"none"}
                                keyboardType={"numeric"}
                                defaultValue={this.state.loanMoney}
                                maxLength={this.state.max}
                                placeholder="输入欠款数"
                                placeholderTextColor='#b2b2b2'
                                autoCorrect={false}
                                style={styles.textInputChangeView}
                                onChangeText={(text)=>{
                                    this.setState({
                                        loanMoney:text,
                                    });
                                    this.input(text)
                                }}/>
                        </View>
                    </View>
                    <View style={[styles.labelView,{borderBottomWidth:0}]}>
                        <Text style={styles.labelLabellingMsg}>还款日期</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <TouchableOpacity
                            style={{width:130,height:40,justifyContent:'center'}}
                            onPress={()=>this._showDateBottomPicker()}>
                            {this.state.repaymentTime===''
                                ?(<View style={{flexDirection:'row',alignItems:'center'}}>
                                    <Text style={[styles.labelInformationMsg,{marginLeft:33}]}>请选择</Text>
                                    <Image
                                        style={{marginLeft:18}}
                                        source={ImageUtil.DropDown}/>
                                </View>)
                                :(<Text style={styles.labelInformationMsg}>{this.state.repaymentTime}</Text>)}
                        </TouchableOpacity>
                        <Text style={styles.labelMsg}>还款金额</Text>
                        <Text style={styles.symbolMsg}>:</Text>
                        <View style={{height:40,width:100,justifyContent:'center',alignItems:'center'}}>
                            <TextInput
                                ref={ (ref)=>this.repaymentMoneyTextInput = ref }
                                autoCapitalize={"none"}
                                keyboardType={"numeric"}
                                maxLength={this.state.max}
                                defaultValue={this.state.repaymentMoney}
                                placeholder="输入还款数"
                                placeholderTextColor='#b2b2b2'
                                autoCorrect={false}
                                style={styles.textInputChangeView}
                                onChangeText={(text)=>{
                                    this.setState({
                                        repaymentMoney:text,
                                    });
                                    this.input(text)
                                }}/>
                        </View>
                    </View>
                </View>
                <View>
                    <Text style={{marginTop:18,marginLeft:15,marginBottom:13,fontSize:27/2}}>备注</Text>
                </View>
                <View style={styles.remarkView}>
                    <TextInput
                        ref={ (ref)=>this.remarkTextInput = ref }
                        multiline={true}
                        autoCapitalize={"none"}
                        defaultValue={this.state.remark}
                        placeholder="请输入此人借款情况描述"
                        placeholderTextColor='#b2b2b2'
                        autoCorrect={false}
                        style={styles.remarkMsg}
                        onChangeText={(text)=>{
                            this.setState({
                                remark:text,
                            })
                        }}/>
                    <View style={styles.allImgView}>
                        {this.state.images.length>0
                            ? this.state.images.map((i,index) =>
                                <View key={i.uri}>
                                    {this.renderImage(i,this.state.images)}
                                </View>)
                            : null}
                        <TouchableOpacity onPress={()=>this.showPop('zoomOut', true, 'Pop modal')}>
                            <Image
                                source={ImageUtil.AddImage}
                                style={styles.remarkImg}/>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
    input=(text)=>{
        for(let i=0;i<text.length;i++){
            if(text[i]==='.'){
                this.setState({
                    max:i+3
                })
            }
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        height:64,
        backgroundColor:'#ffffff',
        alignItems:'center',
        borderBottomWidth:1,
        borderColor:'#e4e4e4'
    },
    titleMsg:{
        fontSize:17,
        color:'#000000',
        marginTop:67/2
    },
    goBackView:{
        position: 'absolute',
        top:65/2,left:15,
    },
    goBackImg:{
        height:18,
        width:18
    },
    completeView:{
        position: 'absolute',
        right:15,bottom:29/2
    },
    completeMsg:{
        color:'#3090dd',
        fontSize:17
    },
    backgroundImg:{
        marginTop:112,
        height:185,
        width:185
    },
    dataView:{
        backgroundColor:'#ffffff',
        marginTop:10,
        alignItems:'center',
        borderBottomWidth:1,
        borderColor:'#cacaca'
    },
    labelView:{
        flexDirection:'row',
        alignItems:'center',
        width:width-30,
        height:44,
        borderBottomWidth:1,
        borderColor:'#e2e2e2'
    },
    labelLabellingMsg:{
        fontSize:27/2,
        color:'#000000'
    },
    symbolMsg:{
        marginLeft:10,
        fontSize:27/2
    },
    labelInformationMsg:{
        marginLeft:17,
        fontSize:27/2,
        color:'#646464'
    },
    remarkView:{
        backgroundColor:'#ffffff',
        borderRadius:5,
        width:width-30,
        marginLeft:15,
        height:150
    },
    remarkMsg:{
        marginTop:14,
        marginLeft:18,
        fontSize:27/2,
        width:width-66,
        height:50
    },
    allImgView:{
        position: 'absolute',
        bottom:10,left:13,
        flexDirection:'row'
    },
    remarkImg:{
        marginLeft:10,
        height:64,
        width:64,
        borderRadius:5
    },
    labelMsg:{
        fontSize:27/2,
        color:'#000000',
        marginLeft:13
    },
    judgmentImg:{
        marginLeft:17,
        height:25/2,
        width:25/2
    },
    textInputView:{
        marginLeft:13,
        fontSize:27/2,
        height:44,
        width:width-195/2
    },
    textInputChangeView:{
        marginLeft:12,
        fontSize:27/2,
        height:44,
        width:100
    },
    overlay:{
        height:44,
        width:230,
        borderBottomWidth:1,
        borderColor:'#eeeff0',
        alignItems:'center',
        justifyContent:'center'
    },
    overlay1:{
        height:44,
        width:230,
        borderWidth:0,
        borderRadius:10,
        alignItems:'center',
        justifyContent:'center'
    },
    PopMsg:{
        textAlign:'center',
        fontSize:14,
        color:'#6590ff',
    },
});
